<?php

namespace App\Kuafu\Shop\Service;

use App\Kuafu\Base\Service\BaseService;
use App\Kuafu\Common\Enum\CodeEnum;
use App\Kuafu\Order\Model\OrderSplitModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\User\Model\User;
use Illuminate\Support\Facades\DB;

class OpenShopService extends BaseService
{
    /**
     * 获取开店-开业报告里面的数据
     */
    public static function getOpenShopInfo(int $shopCode, string $mobile, int $formalUseAt = 0)
    {
        $shopInfo = Shop::query()->where('shopCode', $shopCode)
                        ->first()
                        ->only(['id', 'shopCode', 'name', 'address', 'branch']);

        // 获取当前用户有的店铺列表
        $userInfo = User::query()->where('mobile', $mobile)->first();
        $shopList = [];
        if (!empty($userInfo)) {
            $shopList = ShopService::getShopListByUserAndPlatform($userInfo->id, CodeEnum::PLATFORM_BUSINESS, [
                'status' => [
                    \App\Kuafu\Shop\Enum\CodeEnum::SHOP_STATUS_NORMAL,
                    \App\Kuafu\Shop\Enum\CodeEnum::SHOP_STATUS_PREPARE
                ]
            ]);
        }

        $dataStatic = self::getDataStatic($shopInfo['id'], $formalUseAt, 3);

        return [
            'shopInfo'   => $shopInfo,
            'shopList'   => $shopList,
            'dataStatic' => optional($dataStatic)->toArray()
        ];

    }

    public static function getDataStatic(int $shopId, int $formalUseAt, int $day)
    {
        // 拉对应时间的数据 - $day 天
        return OrderSplitModel::suffix($shopId)
                                     ->query()
                                     ->when($formalUseAt == 0, function ($q) use ($day) {
                                         $q->where('createdAt', '>', strtotime(date('y-m-d')) - 86400 * ($day-1));
                                     }, function ($q) use ($formalUseAt, $day) {
                                         $q->where('createdAt', '>', $formalUseAt);
                                         $q->where('createdAt', '<', $formalUseAt + 86400 * $day);
                                     })
                                     ->select(DB::raw('FROM_UNIXTIME(createdAt, "%Y-%m-%d") as day,
                                      sum(originalPrice) as originalPriceSum,
                                      sum(realPayPrice) as realPayPriceSum,
                                      round(sum(orderStatus) / 3) as orderSum
                                      '))
                                     ->where('shopId', $shopId)
                                     ->where('orderStatus', \App\Kuafu\Order\Enum\CodeEnum::ORDER_STATUS_FINISHED)
                                     ->groupBy('day')
                                     ->get();
    }
}
